<template>
  <div id="relevantQuestionModal">
    <div class="zhezhao" v-if="commonDialogAdd.isShow"></div>
    <el-form label-position="top" ref="form" :model="form" class="" :rules="rules">
      <el-form-item :label="$t('configLazyLoad.robotSeven.relevantInfo1')" prop="type">
        <!--<el-input size="mini" v-model.trim="form.type"></el-input>-->
        <el-select v-model="value" style="width:100%">
          <el-option
            v-for="item in options"
            :key="item._id"
            :label="item.name"
            :value="item._id"
            :disabled="item.pId === ''"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.robotSeven.standardQuestion')" prop="name">
        <el-input size="mini" v-model.trim="form.name"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.robotSeven.similarQuestion')">
        <div class="add" v-for="(item, index) in likenessForm">
          <el-input size="mini" v-model.trim="item.text" class="likenessQuestion" :disabled="old_data.likeness && index < likenessLength && item.text != ''? true : false"></el-input>
          <i class="icon iconfont" @click="addLikenessQuestion(index)" :class="[index? 'icon-zuixiaohua' : 'icon-zhankai']"></i>
        </div>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.robotSeven.status')" prop="status" label-position="top">
        <el-radio-group v-model="form.status">
          <el-radio label="1">{{$t('config.channel.enabled')}}</el-radio>
          <el-radio label="0">{{$t('config.channel.disabled')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.robotSeven.isPushQuestion')" label-position="top">
        <el-radio-group v-model="form.isPush">
          <el-radio label="1">{{$t('public.yes')}}</el-radio>
          <el-radio label="0">{{$t('public.no')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="relatedQuestion">
      <el-row>
        <el-col :span="20">
          <div class="grid-content bg-purple">
            {{$t('configLazyLoad.robotSeven.relevanceQuestion')}}：
            <span>{{$t('configLazyLoad.robotSeven.relevancedQuestion', {num: form.referQuestions.length})}}：</span>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple-light deleteAllQues" @click="deleteAllQues">
            {{$t('configLazyLoad.robotSeven.deleteAll')}}
          </div>
        </el-col>
      </el-row>
      <div class="related_question_detail">
        <el-row v-for="(ques, index) in form.referQuestions">
          <el-col :span="16" class="text">{{index + 1}}、{{ques.name}}</el-col>
          <el-col :span="8" class="operate">
            <span @click="moveUp(index)">{{$t('configLazyLoad.robotSeven.moveUp')}}</span>
            <span @click="moveDown(index)">{{$t('configLazyLoad.robotSeven.moveDown')}}</span>
            <span @click="addRelevantQuestion('edit',ques)">{{$t('public.edit2')}}</span>
            <span @click="deleteQues(index)" class="delete">{{$t('public.delete')}}</span>
          </el-col>
        </el-row>
      </div>
      <el-button class="primary_btn addRelated" @click="addRelevantQuestion">{{$t('configLazyLoad.robotSeven.addRelevanceQuestion')}}</el-button>
    </div>
      <el-form-item :label="$t('configLazyLoad.robotSeven.standardAnswer')" prop="answer" label-position="top">
      </el-form-item>
      <div id="answerEditor" class="unknown-question padding-top" style="margin-top: 20px"></div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelQuestion" class="primary_btn">{{$t('public.cancel')}}</el-button>
      <el-button type="primary" @click="saveQuestion" class="primary_btn">{{$t('public.save')}}</el-button>
    </div>
    <el-dialog :close-on-click-modal="false" :title="commonDialogAdd.title" :visible.sync="commonDialogAdd.isShow" :modal="false" :modal-append-to-body="false">
      <relevant-questions
        @saveReleventQuestion="openReleventQuestion"
        type=""
        :currentRefreQuestion="currentRefreQuestion"
        :disabledQuestionId="disabledQuestionId"
        @close="commonDialogAdd.isShow = false"
        :refresh="randomNum"></relevant-questions>
    </el-dialog>
  </div>
</template>
<script>
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  import {uploadTo7moorRobotImgDomain} from '@/utils/qiniuUtils'
  import {filterXSS} from '@/utils/m7Utils'
  import RelevantQuestions from './relevantQuestions'
  import {checkform} from '@/utils/validate'
  export default {
    name: 'addQuestion',
    data () {
      return {
        commonDialogAdd: {
          isShow: false,
          title: '',
          type: ''
        },
        likenessForm: [
          {
            text: ''
          }
        ],
        form: {
          answer: '',
          likeness: [],
          name: '',
          status: '1',
          type: '',
          isPush: '0',
          _id: '',
          referQuestions: []
        },
        deleteNum: '',
        randomNum: 0,
        quesNum: 0,
        options: [
        ],
        value: '',
        rules: {
          type: [
            {required: true, message: this.$t('configLazyLoad.robotSeven.relevantInfo1'), trigger: 'blur'}
          ],
          name: [
            {required: true, message: this.$t('configLazyLoad.robotSeven.pleaseInputQuestion'), trigger: 'blur'}
          ],
          status: [
            {required: true, message: '', trigger: 'change'}
          ],
          answer: [
            {required: true}
          ]
        },
        editor: {},
        disabledQuestionId: [],
        currentRefreQuestion: {name: '', qId: '', type: ''},
        ifDisabled: false,
        likenessLength: 0,
        old_data: {},
        m7uploaders: []
      }
    },
    props: {
      commonDialog: {
        type: Object,
        default: function () {
          return {
            ifShow: false
          }
        }
      },
      oldData: {
        type: Object,
        default () {
          return {}
        }
      }
    },
    watch: {
      oldData: 'getOldData'
    },
    components: {
      RelevantQuestions
    },
    methods: {
      deleteAllQues () {
        if (this.form.referQuestions.length === 0) {
          this.$message({
            type: 'error',
            message: this.$t('configLazyLoad.robotSeven.noDelete')
          })
        } else {
          this.$confirm(this.$t('configLazyLoad.robotSeven.warningTip3'), this.$t('public.delete'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            this.form.referQuestions = []
            this.$message({
              type: 'success',
              message: this.$t('config.channel.deleteSuccess')
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: this.$t('config.agent.cancelDel')
            })
          })
        }
      },
      getOldData (oldData) {
        if (this.$refs['form']) {
          this.$refs['form'].resetFields()
        }
        this.$store.dispatch('getCache', {type: 'quesTypes'}).then((depts) => {
          this.options = depts || []
        })
        if (oldData.ifdisabled) {
          this.old_data = oldData
          this.likenessLength = this.old_data.likeness.length
        }
        this.form = {
          answer: '',
          likeness: [],
          name: '',
          status: '1',
          type: '',
          isPush: '0',
          _id: '',
          referQuestions: []
        }
//        this.value = this.options[0].value
        this.editor.txt.html('')
        if (oldData.ifdisabled) {
          this.ifDisabled = true
        }
        if (JSON.stringify(oldData) === '{}') {
          return
        }
        if (oldData.isAdd) {
          this.commonDialogAdd.isShow = false
        }
        // 编辑问题获取问题的原数据
        if (oldData.type) {
          this.value = oldData.type
        } else if (this.options.length !== 0) {
          this.value = this.options[0]._id
        }
        this.form._id = oldData._id
        this.form.name = oldData.name
        if (oldData.likeness && oldData.likeness.length !== 0) {
          this.likenessForm = []
          for (let i = 0; i < oldData.likeness.length; i++) {
            if (typeof oldData.likeness[i] === 'object') {
              oldData.likeness[i] = oldData.likeness[i][0]
            }
            this.likenessForm.push({
              text: oldData.likeness[i]
            })
          }
        } else {
          this.likenessForm = [{text: ''}]
        }
        if (oldData.status) {
          this.form.status = oldData.status
        }
        if (oldData.isPush) {
          this.form.isPush = oldData.isPush
        }
        if (oldData.referQuestions && oldData.referQuestions.length !== 0) {
          this.form.referQuestions = []
          for (let i = 0; i < oldData.referQuestions.length; i++) {
            this.form.referQuestions.push({
              _id: oldData.referQuestions[i]._id,
              name: oldData.referQuestions[i].name
            })
          }
        }
        this.form.answer = oldData.answer
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.form.answer)) {
          this.form.answer = this.form.answer.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
        if (checkform(this.form.answer, 'HtmlEnd')) {
          this.form.answer = `<p>${this.form.answer}</p>`
        }
        this.editor.txt.html(filterXSS(this.form.answer))
      },
      saveQuestion () {
        this.form.answer = this.editor.txt.html().replace(/&nbsp;/ig, '')
        let type = this.value
        this.form.type = type
        let likeness = this.likenessForm
        let source = []
        for (let i = 0; i < likeness.length; i++) {
          let _n = likeness[i].text
          if (typeof likeness[i].text === 'object') {
            _n = likeness[i].text[0]
          }
          if (_n && _n !== '') {
            source.push(_n)
          }
        }
        this.form.likeness = source
        if (this.form.answer === '<p><br></p>') {
          this.$message({
            type: 'error',
            message: this.$t('configLazyLoad.robotSeven.submitCheck1')
          })
          return false
        }
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.form.answer)) {
          this.form.answer = this.form.answer.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
        if (this.form.name === undefined) {
          this.$message({
            type: 'error',
            message: this.$t('configLazyLoad.robotSeven.submitCheck2')
          })
          return false
        }
        if (this.form.type === '') {
          this.$message({
            type: 'error',
            message: this.$t('configLazyLoad.robotSeven.submitCheck3')
          })
          return false
        }
        if (this.form.name === '') {
          this.$message({
            type: 'error',
            message: this.$t('configLazyLoad.robotSeven.submitCheck4')
          })
          return false
        }
//        this.$emit('dialogaddquestion', false)
        this.$emit('formData', this.form)
      },
      cancelQuestion () {
        this.$emit('dialogaddquestion', false)
      },
      addLikenessQuestion (index) {
        if (index === 0) {
          this.likenessForm.push({
            text: ''
          })
        } else {
          this.likenessForm.splice(index, 1)
          if (this.likenessForm.length === 1) {
            this.likenessLength = 1
          }
        }
      },
      minusSimilarQuestion (index) {
        this.minusQuesForm.splice(index, 1)
      },
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'robot/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorRobotImgDomain(this.$store.state.session.user._id, 'w-e-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      moveUp (index) {
        if (index === 0) {
          return
        } else {
          let text = this.form.referQuestions[index].name
          let preText = this.form.referQuestions[index - 1].name
          let id = this.form.referQuestions[index]._id
          let preId = this.form.referQuestions[index - 1]._id
          this.form.referQuestions[index - 1].name = text
          this.form.referQuestions[index - 1]._id = id
          this.form.referQuestions[index].name = preText
          this.form.referQuestions[index]._id = preId
        }
      },
      moveDown (index) {
        if (index === (this.form.referQuestions.length - 1)) {
          return
        } else {
          let text = this.form.referQuestions[index].name
          let preText = this.form.referQuestions[index + 1].name
          let id = this.form.referQuestions[index]._id
          let preId = this.form.referQuestions[index + 1]._id
          this.form.referQuestions[index + 1].name = text
          this.form.referQuestions[index].name = preText
          this.form.referQuestions[index + 1]._id = id
          this.form.referQuestions[index]._id = preId
        }
      },
      deleteQues (index) {
        this.$confirm(this.$t('configLazyLoad.robotSeven.warningTip3'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.deleteNum = index
          this.form.referQuestions.splice(index, 1)
          for (let i = 0; i < this.form.referQuestions.length; i++) {
            this.form.referQuestions[i].num = (i + 1) + '、'
          }
          this.$message({
            type: 'success',
            message: this.$t('config.channel.deleteSuccess')
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('config.agent.cancelDel')
          })
        })
      },
      addRelevantQuestion (type, ques) {
        this.randomNum = Math.random()
        this.commonDialogAdd = {
          isShow: true,
          title: this.$t('configLazyLoad.robotSeven.relevanceQuestion'),
          type: 'relevant'
        }
        this.disabledQuestionId = []
        this.commonDialogAdd.isShow = true
        if (type === 'edit') {
          this.currentRefreQuestion.qId = ques._id
          this.currentRefreQuestion.name = ques.name
          this.currentRefreQuestion.type = 'edit'
          this.form.referQuestions.map((item) => {
            if (item._id !== ques._id) {
              this.disabledQuestionId.push(item._id)
            }
          })
        } else {
          this.currentRefreQuestion.name = ''
          this.currentRefreQuestion.qId = ''
          this.currentRefreQuestion.type = 'add'
          this.form.referQuestions.map((item) => {
            this.disabledQuestionId.push(item._id)
          })
        }
        if (this.form._id) {
          this.disabledQuestionId.push(this.form._id)
        }
      },
      openReleventQuestion (questions, type) {
        if (type === 'add') {
          this.quesNum++
          for (let i = 0; i < questions.name.length; i++) {
            this.form.referQuestions.push({
              name: questions.name[i],
              _id: questions.qId[i]
            })
          }
        } else {
          for (let i = 0; i < this.form.referQuestions.length; i++) {
            if (this.form.referQuestions[i]._id === questions.qId[0]) {
              this.form.referQuestions[i].name = questions.name[0]
            }
          }
//          this.form.referQuestions.forEach((item, index) => {
//            if (item._id === questions.qId[0]) {
//              for (let i = 0; i < questions.length; i++) {
//                this.$set(this.form.referQuestions, index, {
//                  name: questions.name[0],
//                  _id: questions.qId[0]
//                })
//              }
//            }
//          })
        }
        this.commonDialogAdd.isShow = false
      }
    },
    mounted () {
      this.$store.dispatch('getCache', {type: 'quesTypes'})
        .then((depts) => {
          this.options = depts || []
        })
      this.editor = new Editor('#answerEditor')
      this.editor.config.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify',  // 对齐方式
        'undo',  // 撤销
        'redo',  // 重复
        // 'code', // 代码
        'table' // 列表
      ]
      this.editor.config.pasteTextHandle = filterXSS
      this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
      this.editor.config.zIndex = 100
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      this.editor.config.lang = editLang
      this.editor.create()
      let div = document.createElement('div')
      div.className = 'w-e-menu'
      div.style.cssText = 'z-index:101;'
      let span = document.createElement('i')
      span.className = 'w-e-icon-image'
      span.id = 'w-e-img-icon'
      div.appendChild(span)
      document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
      this.initUploadImageFile()
      this.getOldData(this.oldData)
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .icon-zhankai
    color $c-main
    margin-left 5px
    font-weight bold
    cursor pointer
  .icon-zuixiaohua
    font-weight lighter
    color #fd6b6b
    margin-left 5px
    cursor pointer
  .likenessQuestion
    width 96%
  .dialog-footer
    text-align center
  .relatedQuestion
    border-bottom 1px dashed #a6a6a6
    margin-bottom 20px
    span
      color $c-prompt
    .deleteAllQues
      color #fd6b6b
      text-align right
      cursor pointer
    .related_question_detail
      padding 5px 0px 10px 20px
      .text
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
      .operate
        text-align right
        span
          color $c-main
          margin-left 10px
          cursor pointer
        .delete
          color #fd6b6b
    .addRelated
      border-color $c-main
      color $c-main
      height 24px
      line-height 24px
      margin 0 0 10px 20px
  #answerEditor
    margin-bottom 20px
</style>
